package anbook.servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import anbook.dao.controller.MemberController;
import anbook.dto.Member;
import anbook.util.Converter;

/**
 * Servlet implementation class AccountServlet
 */
@WebServlet("/Account")
public class AccountServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public AccountServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		response.sendRedirect("/BookProject/");
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		request.setCharacterEncoding("utf-8");
		response.setContentType("text/html; charset=utf8"); 
		
		PrintWriter out = response.getWriter();
		
		String email = request.getParameter("email");
		String nic = request.getParameter("nic");
		String name = request.getParameter("name");
		String password = request.getParameter("password");
		String year = request.getParameter("year");
		String month = request.getParameter("month");
		String day = request.getParameter("day");
		String sex = request.getParameter("sex");
		
		out.println("<meta charset=utf-8>");
		if (email == null || password == null || nic == null || name == null 
			|| year == null || month == null || day == null || sex == null){
			out.println("<script>");
			out.println("alert('값을 입력해주세요.');");
			out.println("history.back(-1);");
			out.println("</script>");
			return;
		}
		String nicname = nic + name;
		MemberController mc = new MemberController();
		Converter con = new Converter();
		Member member = new Member(nicname,email,password,con.convertToDate(year, month, day),sex);
		
		boolean ret = mc.account(member);
		
		out.println("<script>");
		if (ret){
			out.println("alert('회원가입이 성공적으로 되었습니다..');");
			out.println("location.href = '/BookProject/';");
		}else {
			out.println("alert('이메일이 중복됩니다.');");
			out.println("history.back(-1);");
		}
		out.println("</script>");
	}

}
